#!/usr/bin/env python3
"""
Minimal libvirt live memory dump tool

- Dumps RAW memory of running VMs
- Uses VIR_DUMP_LIVE (no VM pause)
- No compression
- No telemetry
- No hashing

Requirements:
  apt install python3-libvirt
"""

import libvirt
import os
import sys
import time

LIBVIRT_URI = "qemu:///system"
DUMP_DIR = "/var/lib/libvirt/dump"   # change if needed


def ensure_dir(path):
    os.makedirs(path, exist_ok=True)


def open_conn():
    conn = libvirt.open(LIBVIRT_URI)
    if conn is None:
        raise RuntimeError("Failed to connect to libvirt")
    return conn


def dump_domain(dom):
    name = dom.name()
    try:
        vmid = dom.ID()
    except libvirt.libvirtError:
        vmid = "unknown"

    ts = int(time.time())
    dump_path = os.path.join(DUMP_DIR, f"{vmid}_{name}_{ts}.mem")

    print(f"[+] Dumping VM '{name}' (ID={vmid}) -> {dump_path}")

    flags = libvirt.VIR_DUMP_LIVE | libvirt.VIR_DUMP_MEMORY_ONLY
    fmt = libvirt.VIR_DOMAIN_CORE_DUMP_FORMAT_RAW

    dom.coreDumpWithFormat(dump_path, fmt, flags)

    print(f"[✓] Dump complete: {dump_path}")


def main():
    ensure_dir(DUMP_DIR)
    conn = open_conn()

    try:
        # Dump ALL running VMs
        for dom_id in conn.listDomainsID():
            dom = conn.lookupByID(dom_id)
            if dom.isActive():
                dump_domain(dom)
    finally:
        conn.close()


if __name__ == "__main__":
    main()
